package Q1

class Main {

}

//两数之和
fun main(){
    println("hello")
}

class Solution {
    // 方法一 枚举算法
    fun twoSum(nums: IntArray, target: Int): IntArray? {
        nums.forEachIndexed{ index, num ->
            for(i in index + 1 until nums.size){
                when{
                    num + nums[i] == target -> return intArrayOf(index, i)
                }
            }
        }
        return intArrayOf()
    }

    //方法二 哈希表
    fun twoSum2(nums: IntArray, target: Int) : IntArray?{
        /*
        hashMapOf<Int, Int>().apply {
            nums.forEachIndexed { index, number ->
                val other = target - number
                if (containsKey(other)) {
                    val otherIndex = get(other) ?: 0
                    return intArrayOf(otherIndex, index)
                }
                put(number, index)
            }
        }
        return intArrayOf()
       */

        hashMapOf<Int, Int>().apply {
            nums.forEachIndexed{index, i ->
                val other = target - i
                if (containsKey(other)) {
                    val otherIndex = get(other) ?: 0
                    return intArrayOf(otherIndex, index)
                }
                put(i, index)
            }
            return intArrayOf()
        }
    }

    fun twoSum3(nums: IntArray, target: Int) : IntArray?{
        val map : MutableMap<Int, Int> = HashMap()
        for(i in nums.indices){
            if(map.containsKey(target - nums[i])){
                return map.get(target - nums[i])?.let { intArrayOf(it,i) }
            }
            map[nums[i]] = i
        }
        return intArrayOf()
    }
}